// 微信小程序公共方法
import cookie from '@/utils/cookie.js'
import config from '@/utils/config.js'

/**
 * 刷新页面
 */
function reload(val) {
        // 页面重载
        const pages = getCurrentPages()
        // 声明一个pages使用getCurrentPages方法
        const curPage = pages[pages.length - 1]
        // 声明一个当前页面
        curPage.onLoad(val) // 传入参数
        curPage.onShow()
        curPage.onReady()
        // 执行刷新
    }

/**
 * 支付
 */
export async function wxPaymentWeiXin(val,status=0){
	
	const params = {
		data: status === 0 ? val:val.data,
		successUrl : val.successUrl,
		successType: val.successType, // 是否是tabBar
		errorUrl : val.errorUrl,
		errorType: val.errorType, // 是否是tabBar
	}
	
	
	function handlePay(type) {
		let str = ''
		let url = ''
		let boolean = false
		
		if(type === 'success'){
			str = '支付成功'
			url = params.successUrl
			boolean  = params.successType
			
			
		}else if(type === 'error'){
			str  ='支付失败，请重新支付'
			url = params.errorUrl
			boolean  = params.errorType
		}
		
		
		// 提示
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: str
		})
		
		
		// 如果有url那就跳转,如果没有那就刷新
		if(url){
			
			setTimeout(()=>{
				
				// 是否是跳转tabBar
				if(boolean){
					uni.switchTab({
						url: url
					});
				}else{
					uni.navigateTo({
						url: url
					});
				}
				
			},2000)
			
		}else{
			reload()
		}
		
	}
	
	
	let payConfig = params.data
	wx.requestPayment({
		timeStamp: payConfig.timeStamp,
		nonceStr: payConfig.nonceStr,
		package: payConfig.package,
		signType: payConfig.signType,
		paySign: payConfig.paySign,
		success: res =>{
			console.log(res, '支付成功',payConfig);
			handlePay('success')
		},
		fail: err => {
			console.log(err, '支付失败',payConfig);
			handlePay('error')
		}
	})
}

/**
 * 小程序上传
 */
export async function wxUpDate(val,type){
	let apiUrl = ''
	
	if(type === 'image'){
		apiUrl = 'api/user/uploadImg'
	}else if(type === 'video'){
		apiUrl = 'api/user/uploadVideo'
	}else if(type === 'audio'){
		apiUrl = 'api/user/uploadVideo'
	}
	
	let token = cookie.get('token')
	
	
	console.log(val, 'type',type);

	let promise = await new Promise((resole,reject)=>{
		uni.uploadFile({
			url: config.baseURL + apiUrl, //上传接口
			filePath: val,
			header: {
				authorization: `Bearer ${token}`
			},
			name: 'file',
			success: (res) => {
				resole(res.data)
			},
			fail:err=> {
				console.log('上传失败',err);
				reject(err)
			}
		});
	})

	return promise
}

